import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/login/index.vue'
import RegisterView from '../views/register/index.vue'
import HomeView from '../views/home/index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/nav/home'  // 根路径重定向到导航首页
    },
    {
      path: '/nav/home',
      name: 'NavHome',
      component: () => import('@/views/nav/home/index.vue'),
      meta: {
        title: '导航首页',
        requireAuth: false  // 标记该路由无需认证
      }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        requireAuth: false
      }
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
      meta: {
        requireAuth: false
      }
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('../views/dashboard/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'system',
          name: 'System',
          redirect: '/system/user',
          meta: { title: '系统管理' },
          children: [
            {
              path: 'user',
              name: 'User',
              component: () => import('../views/system/user/index.vue'),
              meta: { title: '用户管理' }
            },
            {
              path: 'role',
              name: 'Role',
              component: () => import('../views/system/role/index.vue'),
              meta: { title: '角色管理' }
            },
            {
              path: 'menu',
              name: 'Menu',
              component: () => import('../views/system/menu/index.vue'),
              meta: { title: '菜单管理' }
            }
          ]
        },
        {
          path: 'nav',
          name: 'Nav',
          meta: { title: '导航管理', icon: 'Link' },
          children: [
            {
              path: 'link',
              name: 'NavLink',
              component: () => import('../views/nav/link/index.vue'),
              meta: { title: '链接管理' }
            },
            {
              path: 'group',
              name: 'NavGroup',
              component: () => import('../views/nav/group/index.vue'),
              meta: { title: '分组管理' }
            }
          ]
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('token')
  
  // 不需要认证的路由直接放行
  if (to.meta.requireAuth === false) {
    next()
    return
  }
  
  // 已登录状态直接放行
  if (token) {
    next()
    return
  }
  
  // 未登录且需要认证的路由，重定向到登录页
  next('/login')
})

export default router
